package com.example.webbasic.runner;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 基于Redisson的分布式锁测试
 * @author ben
 * @date 2021-11-29 21:05:19 CST
 */
@Component
public class RedissonDistLock implements ApplicationRunner {

	@Autowired
	private RedissonClient rc;

	@Value("${server.port}")
	private String port;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("start: port=" + port);
		
		String mykey = "web-basic-key";
//		RLock rl = rc.getLock(mykey);
		RLock rl = rc.getFairLock(mykey);
		
		IntStream.range(0, 10).forEach(i->{
			rl.lock();
			System.out.println("port=" + port + ", i=" + i + ", 1, now=" + new Date());
			try {
				TimeUnit.SECONDS.sleep(20);
				System.out.println("port=" + port + ", i=" + i + ", 2");
			} catch (InterruptedException e) {
				System.out.println("port=" + port + ", i=" + i + ", 3 异常, e=" + e.getClass());
//				e.printStackTrace();
			} finally {
				rl.unlock();
				System.out.println("port=" + port + ", i=" + i + ", 4, now=" + new Date());
//				try {
//					TimeUnit.SECONDS.sleep(1);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			}
		});
	}

}
